package com.zjdiepu.www.manage.api.other;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.commpent.mapper.other.OtherNoticeVoMapper;
import com.zjdiepu.www.ibiz.other.IOtherNoticeService;
import com.zjdiepu.www.model.other.dto.OtherNotice;
import com.zjdiepu.www.model.other.ext.OtherNoticeExt;
import com.zjdiepu.www.model.other.request.OtherNoticeRequest;
import com.zjdiepu.www.model.other.response.OtherNoticeResponse;

/**
 * 公告Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年06月09日 18时59分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "OtherNoticeController", produces="application/json;charset=UTF-8")
@Api(tags = {"公告"}, produces="application/json;charset=UTF-8")
public class OtherNoticeController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(OtherNoticeController.class);
    @Resource
    private IOtherNoticeService otherNoticeService;
    @Resource
    private OtherNoticeVoMapper otherNoticeVoMapper;

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增公告 <br/>
     * @param otherNotice
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增公告", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute OtherNotice otherNotice) {
    	AbstractSysUser currentUser = getCurrentUser();
    	otherNotice.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	otherNotice.setModifierName(currentUser.getName());
        otherNoticeService.saveUpdateAndDelete(otherNotice, OperateType.add);
        return ApiResponse.success(otherNotice.getId());
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除公告<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除公告", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	otherNoticeService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用公告<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用公告", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	otherNoticeService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用公告<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用公告", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	otherNoticeService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改公告 <br/>
     * @param otherNotice
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改公告", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute OtherNotice otherNotice) {
    	AbstractSysUser currentUser = getCurrentUser();
    	otherNotice.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	otherNotice.setModifierName(currentUser.getName());
    	otherNoticeService.saveUpdateAndDelete(otherNotice, OperateType.edit);
        return ApiResponse.success(otherNotice.getId());
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询公告<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询公告", response = OtherNotice.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       OtherNotice otherNotice = otherNoticeService.selectById(id);
       if(null == otherNotice) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(otherNotice);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询公告 <br/>
     * @param otherNoticeExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询公告",response = OtherNotice.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute OtherNoticeExt otherNoticeExt){
        otherNoticeExt.notDeleted();
        Date dateValidStart = otherNoticeExt.getDateValidStart();
        if(null != dateValidStart) {
        	otherNoticeExt.setDateValidStart(DateUtil.truncAndAddDays(
        			dateValidStart, 0));
        }
        Date dateValidEnd = otherNoticeExt.getDateValidEnd();
        if(null != dateValidEnd) {
        	otherNoticeExt.setDateValidEnd(DateUtil.truncAndAddDays(
        			dateValidEnd, 1));
        }
        otherNoticeExt.setOrderSql("`DATE_VALID` DESC");
        PageVo page = getPage(otherNoticeExt);
        int records = otherNoticeService.countByExt(otherNoticeExt);
        page.setRecords(records);
        if (records > 0) {
            List<OtherNotice> otherNotices = otherNoticeService.selectByExt(otherNoticeExt);
            otherNoticeVoMapper.mapper(otherNotices);
            page.setRows(otherNotices);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询公告 <br/>
     * @param otherNoticeExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询公告",response = OtherNoticeResponse.class, httpMethod="POST")
    @RequestMapping("homePage/list")
    public ApiResponse list(@Validated @ModelAttribute OtherNoticeRequest otherNoticeRequest){
    	getCurrentUser();
    	OtherNoticeExt otherNoticeExt = new OtherNoticeExt();
    	otherNoticeExt.setBaseWhere();
    	//截止今日没有过期
    	otherNoticeExt.setDateValidStart(DateUtil.truncAndAddDays(new Date(), 0));
    	otherNoticeExt.setOrderSql("`CREATED` DESC"); //最新
    	otherNoticeExt.setPage(otherNoticeRequest.getPage());
    	otherNoticeExt.setRows(otherNoticeRequest.getRows());
        int records = otherNoticeService.countByExt(otherNoticeExt);
        
        PageVo page = getPage(otherNoticeExt);
        page.setRecords(records);
        if (records > 0) {
            List<OtherNotice> otherNotices = otherNoticeService.selectByExt(otherNoticeExt);
            List<OtherNoticeResponse> otherNoticeResponses = mapOtherNotices(otherNotices);
            page.setRows(otherNoticeResponses);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
//  ============================================辅助方法===========================================
    
  /**
   * 转换属性：展示
   * @param ywBusinesss
   * @return
   */
  private List<OtherNoticeResponse> mapOtherNotices(List<OtherNotice> otherNotices){
	  if(CollectionUtils.isEmpty(otherNotices)) {
	  		return CollectionInitUtil.emptyList();
	  	}
	  	List<OtherNoticeResponse> otherNoticeResponses = CollectionInitUtil.emptyList();
	  	for(OtherNotice otherNotice : otherNotices) {
	  		OtherNoticeResponse otherNoticeResponse = mapOtherNotice(otherNotice);
	  		if(otherNoticeResponse != null) {
	  			otherNoticeResponses.add(otherNoticeResponse);
	  		}
	  	}
	  	return otherNoticeResponses;
  }
  
  /**
   * 转换属性：展示
   * @param ywBusinesss
   * @return
   */
  private OtherNoticeResponse mapOtherNotice(OtherNotice otherNotice){
  	if(otherNotice == null) {
  		return null;
  	}
  	try {
		OtherNoticeResponse otherNoticeResponse = new OtherNoticeResponse();
		BeanUtils.copyProperties(otherNoticeResponse, otherNotice);
		return otherNoticeResponse;
	} catch (IllegalAccessException | InvocationTargetException e) {
		logger.error("对象拷贝属性出错.", e);
		return null;
	}
  }

}
